package com.ez.supervise.action.biz;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.ez.supervise.action.base.BaseJsonAction;
import com.ez.supervise.core.Page;
import com.ez.supervise.core.Result;
import com.ez.supervise.model.base.BaseEntity;
import com.ez.supervise.model.biz.Cms;
import com.ez.supervise.service.CmsService;
import com.ez.supervise.util.ConvertUtil;
import com.ez.supervise.util.FreemarkerUtil;

public class CmsAction extends BaseJsonAction {
    private static final long serialVersionUID = 8735170970520475073L;
    private Long id;
    private CmsService cmsService;
    private Cms cms;
    private Page page;

    private File doc;
    private String fileName;
    private String ids;

    public String saveCms() {
	getResponse().setContentType("text/html; charset=UTF-8");
	try {
	    String targetDirectory = targetDirectory() + "/" + UPLOAD_FILE_NOTICE;
	    String targetFileName = generateFileName(fileName);
	    // save file
	    if (doc != null) {
		File target = new File(targetDirectory, targetFileName);
		FileUtils.copyFile(doc, target);
		cms.setAttachmentPath(targetFileName);
	    }
	    if (cms.isNew()) {
		cmsService.insert(cms);
	    } else {
		// delete old file
		Cms oldCms = (Cms) cmsService.get(cms.getId());
		if (oldCms != null && StringUtils.isNotBlank(oldCms.getAttachmentPath())) {
		    File file = new File(targetDirectory, oldCms.getAttachmentPath());
		    file.delete();
		}
		cmsService.update(cms);
	    }
	    Result result = new Result(cms.getId());
	    result.setEntity(cms);
	    JsonConfig config = new JsonConfig();
	    config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new",
		"content" });
	    outString(JSONObject.fromObject(result, config).toString());
	} catch (Exception e) {
	    e.printStackTrace();
	    outString(RESULT_FAIL);
	}
	return SUCCESS;
    }

    public String findAllCms() {
	page = new Page();
	String searchField = getRequest().getParameter("searchField");
	String searchValue = getRequest().getParameter("searchValue");
	if (StringUtils.isNotBlank(searchValue)) {
	    page.putCondition(searchField, searchValue.trim());
	}
	int start = Integer.valueOf(getRequest().getParameter("start"));
	int limit = Integer.valueOf(getRequest().getParameter("limit"));
	page.setStart(++start);
	page.setLimit(limit = limit == 0 ? 20 : limit);
	page.addPageInfo();
	page = cmsService.findCmsByPage(page);
	JsonConfig config = new JsonConfig();
	config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new", });

	JSONObject jsonObj = JSONObject.fromObject(page, config);
	outJsonString(jsonObj.toString());
	return SUCCESS;
    }

    public String findAll() {
	page = new Page();
	page.setTotalProperty(0);
	page.setRoot(cmsService.findAll());

	JsonConfig config = new JsonConfig();
	config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new", });

	JSONObject jsonObj = JSONObject.fromObject(page, config);
	// System.out.println(jsonObj.toString());
	outJsonString(jsonObj.toString());
	return SUCCESS;
    }

    /**
     * @return
     */
    public String deleteCms() {
	try {
	    if (id != null && id > 0) {
		String targetDirectory = targetDirectory() + "/" + UPLOAD_FILE_NOTICE;
		Cms oldCms = (Cms) cmsService.get(id);
		if (oldCms != null && StringUtils.isNotBlank(oldCms.getAttachmentPath())) {
		    File file = new File(targetDirectory, oldCms.getAttachmentPath());
		    file.delete();
		}
		cmsService.delete(id);
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }

    /**
     * @return
     * @throws Exception
     */
    public String updateCms() throws Exception {
	String fieldName = getRequest().getParameter("fieldName");
	String fieldValue = getRequest().getParameter("fieldValue");
	String strCmsId = getRequest().getParameter("id");
	try {
	    if (id != null && id > 0) {
		Cms saveCms = new Cms();
		saveCms.setId(id);
		BeanUtils.setProperty(saveCms, fieldName, fieldValue);
		cmsService.update(saveCms);
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }
    
    public String publish() {
	try {
	    if (StringUtils.isNotEmpty(ids)) {
		List idList = ConvertUtil.convertIdList(ids);
		cmsService.publish(idList,BaseEntity.STATUS_PUBLISH_YES);
		List publishList = cmsService.findCmsByPublish();
		boolean flag = createHtml(publishList);
		if(!flag){
		    outJsonString(RESULT_FAIL);
		    return SUCCESS;
		}
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }

    public String recall() {
	try {
	    if (StringUtils.isNotEmpty(ids)) {
		List idList = ConvertUtil.convertIdList(ids);
		cmsService.publish(idList,BaseEntity.STATUS_PUBLISH_NO);
		List publishList = cmsService.findCmsByPublish();
		boolean flag = createHtml(publishList);
		if(!flag){
		    outJsonString(RESULT_FAIL);
		    return SUCCESS;
		}
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }
    
    public static boolean createHtml(List result) {
	boolean flag = true;
	Map contents = new HashMap();
	contents.put("notices", result);
	int count = result == null ? 0 : result.size();
	//生成主文件
	flag = FreemarkerUtil.createHtml("index.ftl", contents, WEB_SITE_PATH, "index.htm");
	//生成具体的页面
	for(int i = 0; i < count; i++){
	    Cms cms = (Cms)result.get(i);
	    contents.put("notice", cms);
	    contents.put("type", "通知公告");
	    flag = FreemarkerUtil.createHtml("notice-id.ftl", contents, WEB_SITE_PATH, "notice-id-" + cms.getId() + ".htm");
	}
	return true;
    }
//    public static boolean createHtml(List result) {
//	boolean flag = true;
//	Map contents = new HashMap();
//	contents.put("notices", result);
//	int count = result == null ? 0 : result.size();
//	int pageSize = 20; //每页20条记录
//	int pageNumber =  count / 20 + (count % 20 == 0 ? 0: 1);
//	//生成主文件
//	flag = FreemarkerUtil.createHtml("index.ftl", contents, WEB_SITE_PATH, "index.htm");
//	//生成具体的页面
//	for(int i = 0; i < count; i++){
//	    Cms cms = (Cms)result.get(i);
//	    contents.put("notice", cms);
//	    flag = FreemarkerUtil.createHtml("notice-id.ftl", contents, WEB_SITE_PATH, "notice-id-" + cms.getId() + ".htm");
//	}
//	contents.put("pageNumber", pageNumber);
//	contents.put("count", count);
//	int currentPage = 0;
//	for(int j = 0; j < pageNumber; j++){
//	    currentPage = j + 1;
//	    contents.put("currentPage", currentPage );
//	    flag = FreemarkerUtil.createHtml("notice-page.ftl", contents, WEB_SITE_PATH, "notice-page-" + currentPage + ".htm");
//	}
//	return true;
//    }
    
    private String targetDirectory() {
	return ServletActionContext.getServletContext().getRealPath("/") + UPLOAD_FILE_PATH;
    }

    private String generateFileName(String fileName) {
	DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
	String formatDate = format.format(new Date());

	int random = new Random().nextInt(10000);
	if (StringUtils.isNotBlank(fileName)) {
	    int position = fileName.lastIndexOf(".");
	    String extension = fileName.substring(position);
	    return formatDate + random + extension;
	} else {
	    return formatDate + random;
	}
    }

    public Long getId() {
	return id;
    }

    public void setId(Long id) {
	this.id = id;
    }

    public static void main(String[] args) {
	Cms cms = new Cms();
	cms.setId(1L);
	// cms.setName("linlinyu");
	JSONObject json = JSONObject.fromObject(cms);

	System.out.println(json);

	JsonConfig config = new JsonConfig();
	config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new", });

	JSONObject jsonObj = JSONObject.fromObject(cms, config);
	System.out.println(jsonObj.toString());
    }

    public void setDoc(File file) {
	this.doc = file;
    }

    public void setDocFileName(String fileName) {
	this.fileName = fileName;
    }

    public void setCmsService(CmsService cmsService) {
	this.cmsService = cmsService;
    }

    public Cms getCms() {
	return cms;
    }

    public void setCms(Cms cms) {
	this.cms = cms;
    }

    public Page getPage() {
	return page;
    }

    public void setPage(Page page) {
	this.page = page;
    }

    public void setIds(String ids) {
	this.ids = ids;
    }

    public String getIds() {
	return ids;
    }

}
